import { withRouter } from "next/router";
import { useState, useEffect } from "react";
import { Form, Input, Button, Radio, Cascader, message } from 'antd';
import Cookies from "js-cookie";
import division_options from '@/china-division';
import emitter from '@/events';
// css
import styles from '@/styles/CommonPersonal.module.scss';
// 组件
import Breadcrumb from '@/components/Breadcrumb';
import Aside from '@/pages_components/personal/Aside';
import Spin from '@/components/Spin';
import avator from "@/public/imgs/personal/avatar.png";
// api
import { myInfoSubmit } from '@/api/personal';
import { getVerifyCode, verifyCode } from '@/api/auth';

let timer = null;

const Mine = ({ router }) => {  

    const [form] = Form.useForm();

    const [loading, setLoading] = useState(false);

    const userInfo = JSON.parse(Cookies.get('userInfo') || '{}');
    const phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;

    const [img, setImg] = useState(process.env.basePath + avator.src);
    
    const [gender, setGender] = useState('');
    const [province, setProvince] = useState('');
    const [city, setCity] = useState('');

    const [nickName, setNickName] = useState('');
    const [showNickName, setShowNickName] = useState(false);

    // 绑定手机号
    const [phone, setPhone] = useState('');
    const [newPhone, setNewPhone] = useState('');
    const [showPhone, setShowPhone] = useState(false);

    useEffect(() => {

        const {headImg, nickname, gender, province, city, phone} = userInfo;
        
        headImg && setImg(headImg);
        nickname && setNickName(nickname);
        gender >= 0 && setGender(gender);
        province && setProvince(province);
        city && setCity(city);
        phone && setPhone(phone);
        
        !nickname && setShowNickName(true);
        !phone && setShowPhone(true);

    }, []);

    // 倒计时
    const [count, setCount] = useState(0);
    useEffect(() => {
        if (count === 0) {
            clearInterval(timer)
            return false
        }
        if (count === 59) {
            timer = setInterval(() => {
                setCount(count => count-1)
            }, 1000)
        }
    }, [count]);

    // 选择地区
    function selectLocation(val) {
        setProvince(val[0]);
        setCity(val[1]);
        submitInfo({
            gender,
            nickName,
            province: val[0],
            city: val[1]
        })
    }
    // 选择性别
    function selectGender(val) {
        setGender(val);
        submitInfo({
            gender: val,
            nickName,
            province,
            city
        })
    }
    // 上传头像
    function uploadHead(file) {
        submitInfo({
            file,
            gender,
            nickName,
            province,
            city
        })
    }
    // 判断昵称
    function submitNickname({ nickName }) {
        if(!nickName || !/^[0-9a-z\u4e00-\u9fa5A-Z-_]{4,20}$/.test(nickName)){
            message.warn('昵称不符合要求，请重新输入')
            return false
        }
        submitInfo({
            gender,
            nickName: nickName,
            province,
            city
        })
    }

    // 提交个人信息数据（除手机号绑定）
    function submitInfo({file, nickName, gender, province, city}) {

        const { id } = userInfo;
        
        const fd = new FormData();
        fd.append('jsonMemberParam', JSON.stringify({userId: id, nickName, gender, province, city}));
        file && fd.append('multipartFile', file);

        setLoading(true);

        myInfoSubmit(fd).then(res => {
            const {code, data} = res;
            if(code === 0 && data){
                Cookies.set('userInfo', JSON.stringify(data), { expires: 7 });
                const {headImg, nickname, gender, province, city} = data;
                headImg && setImg(headImg);
                gender >= 0 && setGender(gender);
                province && setProvince(province);
                city && setCity(city);
                if(nickname){
                    setNickName(nickname);
                    setShowNickName(false);
                    emitter.emit('updateNickname', nickname);
                }
            }
            setLoading(false);
        })
    }

    // 获取验证码
    const getCode = () => {
        setCount(59)
        getVerifyCode(newPhone, 'bind').then(res => {
            if(res.code === 0){
                message.success('验证码已发送');
            }
        })
    }
    // 绑定手机号
    const submitPhone = function({phone: n_phone, code}) {
        if(!phoneReg.test(n_phone)){
            message.warn('请填写正确的手机号');
            return
        }
        if(!code || code && code.length < 6){
            message.warn('请填写正确的验证码');
            return
        }
        const { id } = userInfo;
        const params = {
            purpose: "bind",
            userId: id,
            phone: n_phone,
            smsCode: code
        };
        if(phone){
            params.oldPhoneNumber = phone
        }
        setLoading(true);
        
        verifyCode(params).then(res => {
            const { code, data } = res;
            setLoading(false);
            if(code !== 0){
                return false
            }
            Cookies.set('token', data.token, { expires: 7 });
            Cookies.set('userInfo', JSON.stringify(data), { expires: 7 });
            setShowPhone(false);
            setCount(0);
            setPhone(data.phone);
        })
    }

    // Component
    // 1.头像
    const Avator = (
        <div>
            <img src={img} alt="头像" />
            <label className={styles['operate']} htmlFor="upload_img">重新上传</label>
            <input id="upload_img" type="file" accept=".png, .jpg, .jpeg" onChange={(e) => { uploadHead(e.target.files[0]) }} />
        </div>
    )
    // 2.昵称
    const NickName = (
        <div>
            {
                nickName ? 
                <>
                    <span>{nickName}</span>
                    <em className={styles['operate']} onClick={() => setShowNickName(true)}>修改</em>
                </> : ""
            }
            {
                showNickName ?
                <Form form={form} layout="vertical" onFinish={submitNickname} autoComplete="off">
                    <Form.Item label="昵称" name="nickName">
                        <Input placeholder="4-20个字符，包括中文、英文、数字、“-”、“_”" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" >确定</Button>
                        { nickName && <Button onClick={() => setShowNickName(false)}>取消</Button> }
                    </Form.Item>
                </Form> : ""
            }
        </div>
    )
    // 3.绑定手机号
    const Telephone = (
        <div>
            {
                phone ? 
                <>
                    <span>{phone}</span>
                    <em className={styles['operate']} onClick={() => setShowPhone(true)}>修改</em>
                </> : ""
            }
            {
                showPhone ?
                <Form form={form} layout="vertical" onFinish={submitPhone} autoComplete="off">
                    <Form.Item label="手机号" name="phone">
                        <Input placeholder="请输入手机号" onChange={(e) => { setNewPhone(e.target.value) }} />
                    </Form.Item>
                    <Form.Item label="验证码" name="code" className={styles['merge']}>
                        <Input placeholder="请输入短信验证码" />
                    </Form.Item>
                    <Form.Item label=" " className={styles['merge']}>
                        <Button 
                            disabled={ (!count && !phoneReg.test(newPhone)) || !!count }
                            onClick={() => { getCode() }}
                        >{count ? `${count}s后重发` : '获取验证码'}</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button 
                            type="primary" 
                            htmlType="submit"
                            disabled={ (!count && !phoneReg.test(newPhone)) || !!count }
                        >确定</Button>
                        { phone && <Button onClick={() => setShowPhone(false)}>取消</Button> }
                    </Form.Item>
                </Form> : ""
            }
        </div>
    )
    // 4.性别
    const Gender = (
        <div>
            <Radio.Group value={gender} onChange={(e) => { selectGender(e.target.value) }}>
                <Radio value={0}>保密</Radio>
                <Radio value={1}>男</Radio>
                <Radio value={2}>女</Radio>
            </Radio.Group>
        </div>
    )
     // 4.地区
     const Location = (
        <div>
            {
                province ? 
                <Cascader 
                    className={styles['cascader']}
                    options={division_options} 
                    allowClear={false} 
                    bordered={false} 
                    value={[province,city]}
                    onChange={selectLocation}
                    size="small"
                /> : 
                <Cascader 
                    className={styles['cascader']}
                    options={division_options} 
                    allowClear={false} 
                    bordered={false} 
                    onChange={selectLocation}
                    size="small"
                    placeholder="选择地区"
                />
            }
        </div>
    )

    return (
        <div className={styles['personal-page']}>
            {/* loading */}
            <Spin loading={loading} />
            <div className="max-content">
                 {/* 面包屑 */}
                 <Breadcrumb 
                    params={
                        [
                            { name: '个人中心', url: '/personal' },
                            { name: '个人信息', url: '/personal' }
                        ]
                    } 
                />
                <div className={styles['wrapper']}>
                    {/* 左侧 */}
                    <Aside />
                    {/* 内容 */}
                    <section className={[styles['content'],styles['my-info-content']].join(' ')}>
                    <div className={styles['max-my-info']}>
                        <div className={styles['form-item']}>
                            <label>头像</label>
                            { Avator }
                        </div>
                        <div className={styles['form-item']}>
                            <label>昵称</label>
                            { NickName }
                        </div>
                        <div className={styles['form-item']}>
                            <label>性别</label>
                            { Gender }
                        </div>
                        <div className={styles['form-item']}>
                            <label>地区</label>
                            { Location }
                        </div>
                        <div className={styles['form-item']}>
                            <label>绑定手机号</label>
                            { Telephone }
                        </div>
                    </div>
                    </section>
                </div>
            </div>
        </div>
    )
}

export default withRouter(Mine)